<template>
  <van-button
      class="follow-btn"
      round
      size="small"
      v-if="isFollowed"
      @click="addFollowedClick"
      :loading="isLoading"
    >已关注</van-button>
    <van-button
      v-else
      @click="addFollowedClick"
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="isLoading"
    >关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  data () {
    return {
      isLoading: false // 关注加载中或取消加载中
    }
  },
  // 改变v-model 默认 是自定义属性是value和自定义事件是input的规则
  model: {
    prop: 'isFollowed', // 改变自定义属性，默认是value
    event: 'changeFollow' // 改变自定义规则，默认是 input
  },
  props: {
    // 是否关注了
    isFollowed: {
      type: Boolean,
      required: true
    },
    // value: {
    //   type: Boolean,
    //   required: true
    // },
    // 作者ID
    authorId: {
      type: [String, Object, Number],
      required: true
    }
  },
  methods: {
    // 关注、取消关注
    async addFollowedClick () {
      this.isLoading = true // 加载中
      try {
        // 判断操作行为
        if (this.isFollowed) {
          // 已关注，要取消
          await deleteFollow(this.authorId)
        } else {
          // 未关注，要关注
          await addFollow(this.authorId)
        }
        // 更新关注按钮视图，子父通信  修改父亲 articleInfo 里面的is_followed变量
        // this.$emit('input', !this.isFollowed)
        this.$emit('changeFollow', !this.isFollowed)
      } catch (error) {
        console.dir(error)
        if (error.response.status === 401) {
          // 登录失效或者未登录
          if (this.$store.getters.token) this.$store.commit('setUser', {})
          // 提示一下
          this.$toast.fail('请登录')
          // 跳转
          this.$router.push('/login?url=' + this.$route.path)
        } else {
          this.$toast.fail(this.isFollowed ? '取消失败' : '关注失败')
        }
      }
      // 关注加载中
      this.isLoading = false
    }
  }
}
</script>

<style>

</style>
